package com.ayf.payment.game.api.service.ayb.impl;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.ayb.handler.AybUserTransferHandler;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.entity.ayb.aybUserTransferBind;
import com.ayf.payment.game.api.exception.LogicalException;
import com.ayf.payment.game.api.mapper.ayb.AybUserTransferBindMapper;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.ayb.AybUserTransferBindService;
import com.ayf.payment.game.api.utils.QrCodeUtils;
import com.ayf.payment.game.api.utils.SensitiveDataUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.vo.AybChannelConfigVO;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import com.swwx.charm.zookeeper.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

@Service
@Slf4j
public class AybUserTransferBindServiceImpl implements AybUserTransferBindService {

	private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");


	@Resource
	private MerchantService merchantService;
	@Resource
	private AybUserTransferHandler aybUserTransferHandler;

	@Resource
	private AybUserTransferBindMapper aybUserTransferBindMapper;

	@Autowired
	protected DistributedLock distributedLock;




	/**
	 * 获取绑定爱游宝的二维码
	 * @author lch
	 * @date 2021/12/9
	 * @return
	 */
	@Override
	public String getBindQrCode(MerchantDTO merchantDTO) {
		try {
			Merchant merchant = this.merchantService.find(merchantDTO.getId());

			JSONObject jo = new JSONObject();
			jo.put("type", "channelConfigBind");
			jo.put("merchantId", merchant.getId());
			jo.put("account", merchant.getLoginAccount());
			jo.put("platformCode", PLATFORM_CODE);
			return QrCodeUtils.getBase64(jo.toString());
		} catch (Exception e) {
			throw new LogicalException("商户【{}】获取绑定爱游宝通道二维码异常,异常信息为[{}]", merchantDTO.getName(), e.getMessage());
		}
	}

	/**
	 * 获取解绑爱游宝的二维码
	 * @author lch
	 * @date 2021/12/9
	 */
	@Override
	public String getUnBindQrCode(MerchantDTO merchantDTO) {
		try {
			Merchant merchant = this.merchantService.find(merchantDTO.getId());

			JSONObject jo = new JSONObject();
			jo.put("type", "channelConfigUnBind");
			jo.put("merchantId", merchant.getId());
			jo.put("account", merchant.getLoginAccount());
			jo.put("platformCode", PLATFORM_CODE);
			return QrCodeUtils.getBase64(jo.toString());
		} catch (Exception e) {
			throw new LogicalException("商户【{}】获取解绑爱游宝的二维码异常,异常信息为[{}]", merchantDTO.getName(), e.getMessage());
		}
	}

	/**
	 * 查询绑定结果
	 * @author lch
	 * @date 2021/12/9
	 * @return
	 */
	@Override
	public AybChannelConfigVO getBindResult(MerchantDTO merchantDTO) {
		aybUserTransferBind channelConfig = this.getByMerchantId(merchantDTO.getId());
		boolean lock = false;
		String lockName = "aybgetBindResult-".concat(String.valueOf(merchantDTO.getId())).concat("-").concat(System.getenv("XY_GAME_PAY_LOCK_FLAG"));
		try {
			if (lock = distributedLock.getLock(lockName)) {
				if(channelConfig!=null){
					AybChannelConfigVO vo = BeanConvertUtils.convert(channelConfig, AybChannelConfigVO.class);
					String mobileEncrypt = SensitiveDataUtil.mobileEncrypt(vo.getPhone());
					vo.setPublicKey(null);
					vo.setBindFlag(true);
					vo.setPhone(mobileEncrypt);
					return vo;
				}
				JSONObject inputParam = new JSONObject();
				String traceId = SnowFlakeUtils.getTraceId();
				inputParam.put("traceId",traceId);
				inputParam.put("merchantId", merchantDTO.getId());
				JSONObject data = this.aybUserTransferHandler.getBindInfo(inputParam);
				if(data==null || data.getBoolean("bindFlag")==null || !data.getBoolean("bindFlag")){
					AybChannelConfigVO vo = new AybChannelConfigVO();
					vo.setBindFlag(false);
					return vo;
				}
				AybChannelConfigVO vo = new AybChannelConfigVO();
				vo.setMerchantId(data.getInteger("merchantId"));
				vo.setAybId(data.getLong("aybId"));
				vo.setPublicKey(data.getString("publicKey"));
				vo.setNickName(data.getString("nickName"));
				vo.setPhone(data.getString("phone"));
				vo.setBindFlag(true);

				//保存
				aybUserTransferBind config = BeanConvertUtils.convert(vo, aybUserTransferBind.class);
				this.aybUserTransferBindMapper.insertSelective(config);

				String mobileEncrypt = SensitiveDataUtil.mobileEncrypt(vo.getPhone());
				vo.setPhone(mobileEncrypt);
				return vo;
			} else {
				AybChannelConfigVO vo = new AybChannelConfigVO();
				vo.setBindFlag(false);
				return vo;
			}
		}catch (GetLockFailedException e) {
			LogPortal.error("获取lock失败", e,lockName);
		}  finally {
			if (lock) {
				try {
					distributedLock.releaseLock(lockName);
				} catch (ReleaseLockFailedException e) {
					LogPortal.error("{} 释放失败", e,lockName);
				}
			}
		}
		AybChannelConfigVO vo = new AybChannelConfigVO();
		vo.setBindFlag(false);
		return vo;
	}

	/**
	 * 根据商户id获取
	 * @author lch
	 * @date 2021/12/9
	 */
	@Override
	public aybUserTransferBind getByMerchantId(Integer merchantId) {
		Example example = new Example(aybUserTransferBind.class);
		example.createCriteria().andEqualTo(aybUserTransferBind.Fields.merchantId, merchantId);
		return this.aybUserTransferBindMapper.selectOneByExample(example);
	}

	/**
	 * 查询解绑结果
	 * @author lch
	 * @date 2021/12/9
	 */
	@Override
	public Boolean getUnBindResult(MerchantDTO merchantDTO) {
		aybUserTransferBind channelConfig = this.getByMerchantId(merchantDTO.getId());
		if(channelConfig==null){
			return true;
		}

		JSONObject inputParam = new JSONObject();
		String traceId = SnowFlakeUtils.getTraceId();
		inputParam.put("traceId",traceId);
		inputParam.put("merchantId", merchantDTO.getId());
		JSONObject data = this.aybUserTransferHandler.getBindInfo(inputParam);
		if(data==null || data.getBoolean("bindFlag")==null || !data.getBoolean("bindFlag")){
			//删除库里的绑定关系
			this.removeByMerchantId(merchantDTO.getId());
			return true;
		}

		return false;
	}

	/**
	 * 根据商户id删除
	 * @author lch
	 * @date 2021/12/10
	 */
	@Override
	public void removeByMerchantId(Integer merchantId) {
		Example example = new Example(aybUserTransferBind.class);
		example.createCriteria().andEqualTo(aybUserTransferBind.Fields.merchantId, merchantId);
		this.aybUserTransferBindMapper.deleteByExample(example);
	}


	public static void main(String[] args) {
		String phone = SensitiveDataUtil.mobileEncrypt("17601001780");
		System.out.println(phone);
	}

}
